import React, { memo, useEffect, useState, useRef } from "react";
import Taro, { useRouter } from '@tarojs/taro';
import { View, ScrollView } from '@tarojs/components'
import { Cell, Button, Field, CellGroup, Empty, Popup, Divider, Icon } from '@antmjs/vantui'
import { QRCode } from 'taro3-code'
import { MyIcon, Painter } from "@/components";
import { queryFundList, queryManagerList, queryPersonalList } from "@/services";
import { formatDate } from "@/utils/fomatter";
import './index.scss'
import textPalette from './palette/tests';


function SearchDetail() {
  const router = useRouter()


  const [type, setType] = useState(0)
  const [value, setValue] = useState('')
  const [queryResule, setQueryResule] = useState<any>([])
  const [currentPage, setCurrentPage] = useState(0)
  const [showNotMore, setShowNotMore] = useState(false)
  const [popupShow, setPopupShow] = useState(false)
  const [loading, setLoading] = useState(false)
  const [codeUrl, setCodeUrl] = useState('')
  const painterRef = useRef<any>()
  const saveImage = () => {
    painterRef.current.saveImage()
  }

  useEffect(() => {
    router.params?.type && setType(Number(router.params.type))
    router.params?.value && setValue(router.params.value)
    getResult(Number(router.params?.type), router.params?.value, 0)
  }, [])


  const scrollToLower = () => {
    getResult(type, value, currentPage * 20)

  }

  const getResult = async (searchType, searchValue, offset, flag?: boolean) => {
    let result
    if (!showNotMore) {
      switch (searchType) {
        case 0:
          result = queryManagerList({ managerName: searchValue, limit: 20, offset })
          break
        case 1:
          result = queryFundList({ fundName: searchValue, limit: 20, offset })
          break
        case 2:
          result = queryPersonalList({ userName: searchValue, limit: 20, offset })
          break
        default:
          break
      }
      result.then(res => {
        if (flag) {
          setQueryResule([...res.data])
          res.data.length && setCurrentPage(1)
        } else {
          setQueryResule([...queryResule, ...res.data])
          setCurrentPage(currentPage + 1)

        }
      })

    }


  }
  const serchClick = () => {
    showNotMore && setShowNotMore(false)
    getResult(type, value, 0, true)
  }
  const getDetailUrl = (url) => {
    url && setCodeUrl(url)
    setPopupShow(true)
    setLoading(true)
    Taro.showToast({
      icon: 'loading',
      title: '加载中',
      duration: 1000
    })
  }

  const clickCopy = () => {
    Taro.setClipboardData({
      data: codeUrl
    })
  }

  const MsgListItem = (props) => {
    return (
      <View className='message-box'>
        <View className='message-name text3 black'>
          {
            type == 0 ? props?.managerName : (type == 1 ? props?.fundName : props?.userName)
          }
        </View>
        {
          type == 0 ?
            <CellGroup border={false}>
              <Cell title='法定代表人/执行事务合伙人姓名' value={props?.artificialPersonName ? props.artificialPersonName : '-'} border={false} />
              <Cell title='注册地' value={props?.registerProvince ? props.registerProvince : '--'} border={false} />
              <Cell title='登记编号' value={props?.registerNo ? props.registerNo : '--'} border={false} />
              <Cell title='成立时间' value={props?.establishDate ? formatDate(props.establishDate, null) : '--'} border={false} />
            </CellGroup>
            :
            (
              type == 1 ?
                <CellGroup border={false}>
                  <Cell title='私募基金管理人' value={props?.managerName ? props.managerName : '--'} border={false} />
                  <Cell title='托管人' value={props?.mandatorName ? props.mandatorName : '--'} border={false} />
                  <Cell title='成立时间' value={props?.establishDate ? formatDate(props.establishDate, null) : '--'} border={false} />
                </CellGroup>
                :
                <CellGroup border={false}>
                  <Cell title='证书编号' value={props?.certOde ? props.certOde : '--'} border={false} />
                  <Cell title='机构名称' value={props?.orgName ? props.orgName : '--'} border={false} />
                  <Cell title='诚信记录' value={props?.creditRecordNum ? props.creditRecordNum : '--'} border={false} />
                </CellGroup>
            )


        }
      </View >
    )
  }


  return (
    <View className='search-detail-body'>
      <View className='search-input'>
        <Field
          renderLeftIcon={
            <MyIcon iconName='icon-search-ic' />
          }
          value={value}
          border={false}
          onChange={(e) => setValue(e.detail)}
          renderButton={
            <Button type='default' onClick={() => serchClick()}>搜索</Button>
          }
        />
      </View>
      <View className='scroll-box'>
        {
          queryResule.length ?
            <ScrollView
              className='scroll-body'
              scrollY
              enhanced
              showScrollbar={false}
              onScrollToLower={() => scrollToLower()}
            >


              {

                queryResule.map((result, index) => {
                  return (
                    <View key={index}
                      style={{ marginTop: `${index == 0 ? '0' : '16px'}`, borderBottom: `${index == queryResule.length - 1 ? 'none' : '1px solid #f4f5f7'}` }}
                      onClick={() => getDetailUrl(result.managerUrl ? result.managerUrl : result.detailUrl)}
                    >
                      {
                        MsgListItem(result)
                      }
                    </View>
                  )
                })

              }

            </ScrollView >
            :
            <Empty
              image='https://static.hzddyy.com/taiyi/tt/public_placeholder_nodata.png'
              description='暂无数据'
            />
        }


      </View>
      <Popup show={popupShow} position='bottom' round onClose={() => setPopupShow(false)}>
        <View className='qrpopup-center'>
          <View className='popup-header'>
            <View className='text1 black'>查看详情</View>
            <Icon name='cross' size={36} onClick={() => setPopupShow(false)}></Icon>
          </View>

          <View className='qrcode-body'>
            <View className='text3 black tip'>① 长按保存二维码，扫码查看详情</View>
            <View onLongPress={() => saveImage()}>
              {
                loading ?
                  <QRCode
                    text={codeUrl}
                    size={160}
                    scale={10}
                    errorCorrectLevel='M'
                    typeNumber={2}
                    margin={4}

                  ></QRCode>
                  :
                  null
              }
            </View>

            <Divider contentPosition='center' dashed>或</Divider>
            <View className='text3 black tip'>② 复制链接后，在浏览器打开</View>
            <View className='text2 code-url'>{codeUrl}</View>

          </View>
          <View className='painter'>
            <Painter
              customStyle=''
              palette={(new textPalette()).palette(codeUrl)}
              onImgErr={(err) => { console.error('绘制失败', err) }}
              ref={painterRef}
            />

          </View>
          <Button className='copy-button' onClick={() => clickCopy()}>复制链接</Button>
        </View>
      </Popup >


    </View >


  )
}

export default memo(SearchDetail)
